package top.fyxxxx.utils;

import org.dom4j.Element;

import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class SQLHelper {
    private static Connection conn;
    private static Statement state;
    public static Connection getConnection() throws Exception {
        if(conn==null||conn.isClosed()){
            synchronized (SQLHelper.class){
                if(conn==null||conn.isClosed()){
                    conn=createConnection();
                }
            }
        }
        return conn;
    }
    public static Statement getStatement() throws Exception{
        if(state==null||state.isClosed()){
            synchronized (SQLHelper.class){
                if(state==null||state.isClosed()){
                    state=getConnection().createStatement();
                }
            }
        }
        return state;
    }
    private static Connection createConnection() throws Exception {
        FastInputReader in=new FastInputReader(new FileInputStream(getConfig()));
        String DB_URL,USER,PASS;
        String xml=in.getAll();
        Element root=XmlUtils.parseXml(xml);
        // 注册 JDBC 驱动
        Class.forName(root.elementText("JDBC_DRIVER"));
        DB_URL=root.elementText("url");
        USER=root.elementText("username");
        PASS=root.elementText("password");
        return DriverManager.getConnection(DB_URL,USER,PASS);
    }

    /**
     * 获取配置文件，可按实际需求更改
     * @return 配置文件
     */
    private static File getConfig(){
        String confDir=SQLHelper.class.getResource("/..").getPath()+File.separator;
        return new File(confDir+"SQLConf.xml");
    }
}
